package com.spzx.common.rabbit.config;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setupCallbacks();
    }

    private void setupCallbacks() {
        /**
         * 只确认消息是否正确到达 Exchange 中,成功与否都会回调
         *
         * @param correlation 相关数据  非消息本身业务数据
         * @param ack         应答结果
         * @param reason      如果发送消息到交换器失败，错误原因
         */
        rabbitTemplate.setConfirmCallback(((correlationData, ask, reason) ->{
//            String msgId = correlationData.getId();
            if (ask){
                //消息到交换器成功
                System.out.println(correlationData);
                log.info("消息发送到Exchange成功：{}", correlationData);
            }else {
                //消息到交换器失败
                log.error("消息发送到Exchange失败：{}", reason);
            }
        } ));
        rabbitTemplate.setReturnsCallback(returned -> {
            log.error("返回: " + new String(returned.getMessage().getBody())
                    + "\n 响应码: " + returned.getReplyCode()
                    + "\n 响应消息: " + returned.getReplyText()
                    + "\n 交换机: " + returned.getExchange()
                    + "\n 路由: " + returned.getRoutingKey());
        });
    }
}
